package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.company.entity.Admin;
import com.fz.us.admin.company.service.AdminService;
import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.company.bean.EnumManage;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Sets;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 成员信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-03 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/member")
public class MemberController extends BaseController {

    private static final long serialVersionUID = 8590615741679949857L;

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private PostService postService;
    /**
     * 新建页面
     */
    @RequestMapping(value = "create", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user) {

        return "/main/company/member_create";
    }

    /**
     * 成员登录账号校验
     */
    @RequestMapping(value = "validate/account", method = RequestMethod.POST)
    @ResponseBody
    public String validate_account(@CurrentUser User user,
                                   String account) {

        Result result = userService.validateAccount(account);

        return String.valueOf(result.getState() == 1);
    }

    /**
     * 新建操作
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public Object create(@CurrentUser User user,
                         String account,
                         String password,
                         String name) {
        Company company = user.getCompany();

        Result result = userService.createMember(account, password, name, company);

        return ajaxJson(result);
    }

    /**
     * 默认职责更新
     */
    /**
     * 点击分配岗位弹出dialog中的确定按钮事件
     * @return
     */
    @RequestMapping(value = "defaultDuty", method = RequestMethod.POST)
    public Object defaultDuty(@CurrentUser User user,
                         String userId,String keyId){
        if(StringUtils.isEmpty(keyId) || StringUtils.isEmpty(userId)){
            return ajaxJson(resultService.fail("选择人员职责信息！"));
        }
        User users = userService.get(userId);
        Map dmap = new HashMap<String, Object>();
        dmap.put("ifMain", 1);
        dmap.put("user", users);
        dmap.put("state", BaseEnumManager.StateEnum.Enable);
        String hql = "from Duty where ifMain=:ifMain and user=:user and state=:state";
        List<Duty> dutys = dutyService.getList(hql,dmap);
        for(Duty info:dutys){
            if(!info.getId().equals(keyId)){
                info.setIfMain(null);
                dutyService.update(info);
            }
        }
        Duty duty=dutyService.get(keyId);
        if(duty.getIfMain() ==null ){
            duty.setIfMain(1);
        }else{
            duty.setIfMain(null);
        }
        dutyService.update(duty);
        Result result = resultService.success();
        return ajaxJson(result);
    }

    /**
     * 查看职责
     */
    @RequestMapping(value = "dutyView/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dutyView(@CurrentUser User user, Model model,
                             @PathVariable String keyId){
        model.addAttribute("keyId", keyId);
        User users  = userService.get(keyId);
        List<Duty> dutyList = dutyService.getUserDutyList(users);
        ArrayList<Map<String,Object>> dutyArrayList = new ArrayList<Map<String, Object>>();
        Map<String,Object> rMap;
        for(Duty dutys:dutyList){
            rMap=new HashMap<String, Object>();
            if (dutys.getPower() != null) {
                rMap.put("department", dutys.getPower().getDepartment());
                rMap.put("post",dutys.getPower().getPost());
            }
            rMap.put("id",dutys.getId());
            rMap.put("checked","");
            if(dutys.getIfMain()!=null && dutys.getIfMain() == 1){
                rMap.put("checked", "checked");
            }
            dutyArrayList.add(rMap);
        }
        model.addAttribute("dutyArrayList", dutyArrayList);
        return "/main/company/member_dutyView";
    }

    /**
     * 分配职权
     */

    @RequestMapping(value = "configView/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String configView(@CurrentUser User user, Model model,
                              @PathVariable String keyId){
        model.addAttribute("keyId", keyId);
        User users = userService.get(keyId);
        List<Duty> dutyList= dutyService.getUserDutyList(users);

        Set<Department> departmentSet= Sets.newHashSet();
        // Set<Post> postSet1 =Sets.newHashSet();
        for(Duty duty:dutyList){
            departmentSet.add(duty.getPower().getDepartment());
            //   postSet1.add(duty.getPost());
        }
        Company company = user.getCompany();
        List<Map<String,Object>> departArrayList = new ArrayList<Map<String, Object>>();
        List<Map<String,Object>> postArrayList = new ArrayList<Map<String, Object>>();

        List<Department> departments=  departmentService.getAllDepartments(company);

        Map<String,Object> rmap=null;
        Map<String,Object> pmap=null;
        for(Department department:departments){
            rmap=new HashMap<String, Object>();
            rmap.put("departId", department.getId());
            rmap.put("departName", department.getName());
            rmap.put("checked", "");

            if(departmentSet.contains(department)){
                rmap.put("checked", "checked");
                List<Power> powerList = powerService.getByDepartId(department.getId());
                if(powerList!=null && powerList.size()>0){
                    Set<Post> postSet =new HashSet<Post>();
                    Set<Post> postSet1 = getDutyByDepartment(dutyList, department);
                    for(Power power:powerList){
                        if(power.getPost()!=null){
                            postSet.add(power.getPost());
                        }
                    }
                    if(postSet!=null && postSet.size()>0){
                        for(Post post:postSet){
                            pmap=new HashMap<String, Object>();
                            pmap.put("id",department.getId()+"-"+post.getId());
                            pmap.put("name", department.getName() + "-" + post.getName());
                            if(postSet1.contains(post)){
                                pmap.put("checked", "checked");
                            }else{
                                pmap.put("checked", "");
                            }
                            postArrayList.add(pmap);
                        }
                    }
                }
            }
            departArrayList.add(rmap);
        }
        model.addAttribute("departArrayList", departArrayList);
        model.addAttribute("postArrayList", postArrayList);
        return "/main/company/member_configView";
    }

    /**
     * 点击分配岗位弹出dialog中的部门checkBox，查询出该部门下的岗位
     * @return
     */
    @RequestMapping(value = "configPost", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> configPost(@CurrentUser User user, String rowId){
        Department department=departmentService.get(rowId);
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        List<Power> powerList=powerService.getByDepartId(rowId);
        Set<Post> postSet;
        Map<String,Object> rmap;
        if(powerList!=null && powerList.size()>0){
            postSet=new HashSet<Post>();
            for(Power power:powerList){
                if(power.getPost()!=null){
                    postSet.add(power.getPost());
                }
            }
            if(postSet!=null && postSet.size()>0){
                for(Post post:postSet){
                    rmap=new HashMap<String, Object>();
                    rmap.put("id",rowId+"-"+post.getId());
                    rmap.put("name",department.getName()+"-"+post.getName());
                    rmap.put("checked","");
                    dataRows.add(JSONObject.fromObject(rmap));
                }
            }
        }
        data.put("state","200");
        data.put("rows", JSONArray.fromObject(dataRows));
        data.put("title", "操作状态");
        return data;

    }

    /**
     * 点击分配岗位弹出dialog中的确定按钮事件
     * @return
     */
    @RequestMapping(value = "config", method = RequestMethod.POST)
    public Object config(@CurrentUser User user,
                         String rowIds,String keyId){
        JSONArray dataRows = JSONArray.fromObject(rowIds);
        User users = userService.get(keyId);
        Set<Power> powerSet=Sets.newHashSet();
        List<Duty> dutyList= dutyService.getUserDutyList(users);
        for(Duty duty:dutyList){
            if(duty.getPower()!=null){
                powerSet.add(duty.getPower());
            }
        }
        for(int i=0;i<dataRows.size();i++){
            JSONObject obj = dataRows.getJSONObject(i);
            String rowId = obj.getString("id");
            String departId = rowId.split("-")[0];
            String postId = rowId.split("-")[1];
            Department department = departmentService.get(departId);
            Post post = postService.get(postId);
            Power power=powerService.getPowerByDepartAndPost(department, post);
            if(power==null){
                continue;
            }
            if(powerSet.contains(power)){
                continue;
            }
            Duty duty= new Duty(users,power);
            duty.setCompany(users.getCompany());
            duty.setDutyState(EnumManage.DutyState.Default);
            dutyService.save(duty);
        }
        Result result = resultService.success();
        return ajaxJson(result);
    }
    /**
     * 根据部门来查找职责
     * @return
     */
    public Set<Post> getDutyByDepartment(List<Duty> dutyList, Department department){
        Set<Post> postSet =Sets.newHashSet();
        for(Duty duty:dutyList){
            if(duty.getPower().getDepartment() == department){
                postSet.add(duty.getPower().getPost());
            }
        }
        return postSet;
    }

    /**
     * 删除职责信息
     * @return
     */
    @RequestMapping(value = "deleteDuty", method = RequestMethod.POST)
    public Object deleteDuty(@CurrentUser User user ,String keyId){
        if(StringUtils.isEmpty(keyId)){
            return resultService.fail("请选择职责!");
        }
        Duty duty = dutyService.get(keyId);
        duty.setState(BaseEnumManager.StateEnum.Delete);
        dutyService.update(duty);
        return ajaxJson(resultService.success("删除成功！"));
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "update/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String update(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {

        model.addAttribute("keyId", keyId);
        return "/main/company/member_update";
    }

    /**
     * 编辑操作
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Object update(@CurrentUser User user,
                         String keyId,
                         String role) {
        Company company = user.getCompany();

        User member = userService.get(keyId);

        Result result = resultService.successWithId(member.getId());

        return ajaxJson(result);
    }

    /**
     * 获取详情
     */
    @RequestMapping(value = "read/{keyId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object read(@CurrentUser User user,
                       @PathVariable String keyId) {
        User member = null;
        if (StringUtils.isNotBlank(keyId)) {
            member = userService.get(keyId);
        }
        if (member == null){
            member = new User();
        }

        Map<String, Object> dataMap = userService.getMemberListMap(member);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();

        // 排序
        /*
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        } else {
            order = Order.order("pinYin", SearchEnum.OrderType.asc);
        }

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        */
        SearchResultPaging searchResult = userService.pagingCompanyMember(null,null,null, company, BaseEnumManager.StateEnum.Enable);
        List<User> userList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (User entity : userList) {
            Map<String, Object> map = userService.getMemberListMap(entity);
            Admin admin = adminService.get(entity.getAdminId());
            if(admin != null)     {
                map.put("useremail", admin.getUseremail());
                map.put("usermobile", admin.getUsermobile());
            }
            map.put("ifMain", "") ;
            Set<Duty> dutySet = entity.getDutySet();
            if(dutySet != null && dutySet.size()>0){
                for(Duty duty:dutySet){
                    map.put("dutyId", duty.getId());
                    if(duty.getState() != null && StringUtils.equals("Enable", duty.getState().value()) && duty.getIfMain() == 1){
                        map.put("ifMain", "1") ;
                        break;
                    }
                }
            }

            dataRows.add(map);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }

    /**
     * 选择成员(单个)
     */
    @RequestMapping(value = "dialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialog(@CurrentUser User user) {

        return "/main/company/member_dialog";
    }

    /**
     * 选择成员(多个)
     */
    @RequestMapping(value = "dialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialogs(@CurrentUser User user,@RequestParam(required = false) String sids, Model model) {
        model.addAttribute("sids",sids);

        if (StringUtils.isNotBlank(sids)) {
            String[] uids = StringUtils.split(sids,",");
            ArrayList<User> users = new ArrayList<User>();
            for (String uid : uids) {
                User u = userService.get(uid);
                users.add(u);
            }
            model.addAttribute("selectedUsers",users);
        }

        return "/main/company/member_dialogs";
    }

}
